package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * C端用户业务接口
 *
 * @Author Vsunks.v
 * @Date 2023/5/6 15:14
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    JwtProperties jwtProperties;

    @Autowired
    UserMapper userMapper;

    /**
     * 微信登录
     *
     * @param userLoginDTO 登录授权码
     * @return 登录后的信息
     */
    @Override
    public Result<UserLoginVO> wxLogin(UserLoginDTO userLoginDTO) {

        // 换取openid
        String openid = getOpenId(userLoginDTO);


        //通过openid判断当前用户是否为新用户，是则注册
        User user = userMapper.selectByOpenId(openid);
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 为微信用户数生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        // 封装数据并返回
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 换取openId
     *
     * @param userLoginDTO 登录授权码
     * @return
     */
    private String getOpenId(UserLoginDTO userLoginDTO) {
        // 请求微信服务接口，换取tokenId
        Map<String, String> paramMap = Map.of(
                "appid", weChatProperties.getAppid(),
                "secret", weChatProperties.getSecret(),
                "js_code", userLoginDTO.getCode(),
                "grant_type", WeChatConstant.GRANT_TYPE
        );
        String json = HttpClientUtil.doGet(weChatProperties.getLoginUrl(), paramMap);

        // 没必要定义一个类用来封装响应结果，直接使用JSONObject接收，该类提供了getXxxx根据key获取json中的value数据
        JSONObject jo = JSON.parseObject(json);
        String openId = jo.getString(WeChatConstant.OPEN_ID);

        return openId;
    }
}
